<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

/**
 * Format a mysql formatted date to a localized date
 *
 * @param date : a mysql formatted date, default = current date
 * @param smartformat : a smart format to use (see FRAMEWORK_HOME/date/locales/date.xml), default = localized-user-time-format
 * @param lang : lang to use in ISO format, ex : EN, default = current context lang
 * 
 * @example {date date="2008-10-09 11:06:19"}
 * 
 * @return string
 */
function smarty_function_date($params, &$smarty)
{
	$default_smart_format = "localized-user-time-format";

	// === Get the date
	if(!isset($params['date']) || $params['date'] == "")
	{
		$date = date("Y-m-d H:i:s");
        if(isset($params['isNull']) && $params['isNull'] == true)
        {
            return "";
        }
	}
	else
	{
		if (!preg_match('#^(\\d{4})\-(\\d{1,2})\-(\\d{1,2})(\s+(\\d{1,2}):(\\d{1,2}):(\\d{1,2}))?$#', $params['date']))
		{
			return $params['date']; 
		}
		$date = $params['date'];
	}
	
	// === Get the smartformat to use
	if(!isset($params['smartformat']) || $params['smartformat'] == "")
	{
		$smartFormat = $default_smart_format;
	}
	else
	{
		$smartFormat = $params['smartformat'];
	}
	
	// === Get the lang to use
	if(!isset($params['lang']) || $params['lang'] == "")
	{
		$lang =  f_core_Context::getInstance()->getDisplayLang();
	}
	else
	{
		$lang = $params['lang'];
	}	

	// === Return the date
	return f_date_DateFormat::smartFormatByLang($date, $smartFormat, $lang);
}